import React, { useState } from 'react';
import {
  Box,
  TextField,
  Button,
  Typography,
  Alert,
  Collapse
} from '@mui/material';
import { useNavigate, Navigate } from 'react-router-dom';
import './login.css';

export default function Login() {
  const navigate = useNavigate();
  const [formData, setFormData] = useState({
    username: '',
    password: '',
  });
  const [error, setError] = useState(false);

  // If already logged in, redirect to dashboard
  if (localStorage.getItem('isAuthenticated') === 'true') {
    return <Navigate to="/dashboard" replace />;
  }

  const handleChange = (prop) => (event) => {
    setFormData({ ...formData, [prop]: event.target.value });
    setError(false);
  };

  const handleLogin = (e) => {
    e.preventDefault();
    try {
      if (formData.username.trim() === 'admin' && formData.password.trim() === 'admin') {
        localStorage.setItem('isAuthenticated', 'true');
        localStorage.setItem('userRole', 'admin');
        navigate('/dashboard', { replace: true });
      } else if (formData.username && formData.password) {
        localStorage.setItem('isAuthenticated', 'true');
        localStorage.setItem('userRole', 'user');
        navigate('/dashboard', { replace: true });
      } else {
        setError(true);
      }
    } catch (error) {
      console.error('Navigation error:', error);
      setError(true);
    }
  };

  return (
    <div className="loginContainer">
      <div className="loginLeft">
        <div className="loginHi">Welcome Back</div>
        <div className="loginIllustration">
          <img 
            src="https://images.unsplash.com/photo-1517248135467-4c7edcad34c4?w=800&auto=format&fit=crop&q=60" 
            alt="Login illustration"
            className="illustrationImage"
          />
        </div>
      </div>
      <div className="loginRight">
        <Collapse in={error}>
          <Alert 
            severity="error" 
            onClose={() => setError(false)} 
            className="errorAlert"
            sx={{
              '& .MuiAlert-icon': {
                fontSize: '24px'
              }
            }}
          >
            Invalid username or password
          </Alert>
        </Collapse>
        
        <div className="loginForm">
          <Typography variant="h4" component="h1" className="loginTitle">
            Login
          </Typography>

          <Box component="form" onSubmit={handleLogin} className="formBox">
            <TextField
              required
              fullWidth
              id="username"
              placeholder="Username"
              name="username"
              autoComplete="username"
              value={formData.username}
              onChange={handleChange('username')}
              className="loginInput"
              variant="outlined"
              InputProps={{
                startAdornment: (
                  <span className="inputIcon">👤</span>
                ),
                sx: {
                  height: '48px',
                }
              }}
            />
            <TextField
              required
              fullWidth
              name="password"
              placeholder="Password"
              type="password"
              id="password"
              autoComplete="current-password"
              value={formData.password}
              onChange={handleChange('password')}
              className="loginInput"
              variant="outlined"
              InputProps={{
                startAdornment: (
                  <span className="inputIcon">🔒</span>
                ),
                sx: {
                  height: '48px',
                }
              }}
            />

            <Button
              type="submit"
              fullWidth
              variant="contained"
              className="loginButton"
            >
              Login
            </Button>
          </Box>
        </div>
      </div>
    </div>
  );
} 